<style lang="scss"></style>

<script>

import PatrolGroupForm, { WeekdaysMap } from './patrolGroupForm.vue'
import DialogContent from "@/components/DialogContent/index.vue"
import { patrolGroupDetails } from '@/api/watchman'
export default {
  components: {
    PatrolGroupForm,
    DialogContent
  },
  props: {
    groupId: {
      type: [Number, null],
      required: false,
      default: null
    },
    value: {
      type: Boolean,
      required: true,
      default() {
        return false
      }
    },
    title: {
      type: String,
      required: false,
      default: '查看巡防小组'
    },
    confirmText: {
      type: String,
      required: false,
      default: '确定'
    }
  },
  data() {
    return {
      patrolGroup: null,
      isLoading: false
      // form: {
      //     groupName: '',
      //     membersSelected: [],
      //     isIgnoreLegalHolidays: false,
      //     rules: [],
      // },
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isShow() {
      return this.dialogVisible && typeof this.groupId === 'number'
    },
    isActionDisabled() {
      return this.isLoading
    },
    members() {
      if (!this.patrolGroup) { return [] }

      const { user } = this.patrolGroup
      if (!Array.isArray(user)) { return [] }

      return user
    },
    plans() {
      if (!this.patrolGroup) { return [] }

      const { rule } = this.patrolGroup
      if (!Array.isArray(rule)) { return [] }

      const classes = rule.map(item => item.classes)
      const ids = classes.map(item => item.id)
      const uniqueIds = [...new Set(ids)]
      const result = uniqueIds.map(id => classes.find(item => item.id === id))

      return result
    },
    particularDates() {
      if (!this.patrolGroup) { return [] }

      const { date } = this.patrolGroup
      if (!Array.isArray(date)) { return [] }

      const ids = date.map(item => item.id)
      const uniqueIds = [...new Set(ids)]
      const result = uniqueIds.map(id => date.find(item => item.id === id))

      return result
    },
    form() {
      const form = {
        groupName: '',
        membersSelected: [],
        particularDatesSelected: [],
        isIgnoreLegalHolidays: false,
        rules: []
      }

      if (!this.patrolGroup) return form

      const { name, rule, user, legal_holidays, date } = this.patrolGroup

      form.groupName = name
      form.membersSelected = this.memberSelectedFormatter(user)
      form.particularDatesSelected = this.particularDatesSelectedFormatter(date)
      form.rules = this.rulesFormatter(rule)
      form.isIgnoreLegalHolidays = legal_holidays === 1
      return form
    }
  },
  watch: {
    isShow(isShow) {
      isShow && this.initData()
    }
  },
  methods: {
    closeDialog() {
      this.dialogVisible = false
    },
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    memberSelectedFormatter(members) {
      return members.map(member => member.id)
    },
    particularDatesSelectedFormatter(dates) {
      if (!Array.isArray(dates)) return []
      return dates.map(date => date.id)
    },
    rulesFormatter(rules) {
      const weekdaysMap = Object.keys(WeekdaysMap).map(item => ({
        ...WeekdaysMap[item],
        key: item
      }))

      return rules.map(item => {
        const { classes, weeks } = item
        const dayIds = JSON.parse(weeks) ?? []
        return {
          patrolPlan: classes,
          days: dayIds.map(id => weekdaysMap.find(item => item.value === id))
        }
      })
    },
    async getPatrolGroupDetails() {
      const result = await patrolGroupDetails(this.groupId)
      this.patrolGroup = result.data
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getPatrolGroupDetails()
      ])

      const failTask = result.filter(task => task.status === 'rejected')
      if (failTask.length <= 0) return

      throw failTask.at(0).reason
    },
    async initData() {
      try {
        this.isLoading = true

        await this.sleep(300)
        await this.loadData()

        this.isLoading = false
      } catch (error) {
        this.isLoading = false
        console.log(error)
        this.$message.error('加载数据失败')
      }
    }
  }
}
</script>

<template>
  <DialogContent :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
    width="40%"
    destroy-on-close>
    <div v-loading="isLoading" class="body">
      <PatrolGroupForm
        v-model="form"
        :show-create-rule-btn="false"
        :show-remove-rule-btn="false"
        :members="members"
        :plans="plans"
        :particular-dates="particularDates"
        disabled
      />
    </div>
    <div slot="footer">
      <el-button
        type="primary"
        :disabled="isActionDisabled"
        @click="closeDialog"
      >
        {{ confirmText }}
      </el-button>
    </div>
  </DialogContent>
</template>
